/**
 * Created by zhengyi.fu on 2018/8/31.
 */
import Fly from 'flyio/dist/npm/wx'
import config from '../configs/appconfig'
import constants from '../constants/constants'
import global from '../utils/globalfun'
import {removeUserInfo, getStorage} from '@/utils/wechat'
import wx from '@/utils/wx'

const fly = new Fly()
const host = appHostSet()
fly.config.timeout = 10000;

function appHostSet() {
  switch (config.STATIS) {
    case config.ENVIRONMENT.TEST:
      return 'http://172.16.8.147'
    case config.ENVIRONMENT.DEVELOP:
      return 'http://172.16.8.147'
    case config.ENVIRONMENT.PRODUCE:
      return 'http://app.fashionfinger.com'
    case config.ENVIRONMENT.REALEASE:
      return 'https://app.fashionfinger.com'
  }
}

// 添加请求拦截器
fly.interceptors.request.use((request) => {
  // request.headers["X-Tag"] = "flyio";
  // request.headers['content-type']= 'application/json';
  request.headers = {
    'X-Tag': 'flyio',
    'content-type': 'application/json',
    'clientType': 'mini',
    'bloggerUid': config.CURRENT_BLOGGER
  }
  let authParams = {
    // 公共参数
    'categoryType': 'SaleGoodsType@sim',
    'streamNo': 'wxapp153570682909641893',
    'reqSource': 'MALL_H5',
    'appid': 'string',
    'timestamp': new Date().getTime(),
    'sign': 'string'
  }
  if (global.isArrayEmpty(request.body)) {
    request.body = {
      bloggerUid: '',
      access_token: '',
      uid: ''
    }
  }
  try {
    request.body.bloggerUid = config.CURRENT_BLOGGER
  } catch (e) {
    console.log(e)
  }
  const userInfo = global.getUserInfo();
  if (!global.isNull(userInfo)) {
    request.body.access_token = userInfo.access_token
    request.body.uid = userInfo.uid
  }
  request.body && Object.keys(request.body).forEach((val) => {
    if (global.isEmpty(request.body[val])) {
      delete request.body[val]
    }
    ;
  })
  request.body = {
    ...request.body
    // ...authParams
  }
  console.log(request)
  return request
})

// 添加响应拦截器
fly.interceptors.response.use(
  (res, promise) => {
    wx.hideLoading()
    if (res.data) {
      if (res.data.status == 0) {
        res.data.successCode = 1
      } else if (res.data.status == 1001 || res.data.status == 1002 || res.data.status == 1003 || res.data.status == 1004 || res.data.status == -3) { // 未登录
        removeUserInfo()
        global.jumper("/pages/login/main")
        res.data.successCode = 0
      } else {
        res.data.successCode = 0
      }
    } else {
      res.data.successCode = 0
    }
    return promise.resolve(res.data)// 请求成功之后将返回值返回
  },
  (err, promise) => {
    // 请求出错，根据返回状态码判断出错原因
    wx.hideLoading()
    console.log(err)
    let title = ''
    let res = {}
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
        case 401:
        case 403:
        case 404:
        case 500:
        case 501:
        case 503:
          title = '服务器开小差，请稍后再试！'
          break
        case 408:
        case 504:
          title = '请求超时，请检查您的网络'
          break
        case 502:
        case 505:
          title = '网络连接错误，请检查您的网络'
          break
        default:
          title = '服务器开小差，请稍后再试！'
      }
      res.status = err.response.status
    } else {
      if (err.status == 1) {
        title = '请求超时，请检查您的网络'
      } else {
        title = '服务器开小差，请稍后再试！'
      }
      res.status = err.status
    }
    wx.showToast({title: title, icon: "none"})
    res.message = title
    res.successCode = 0
    return promise.resolve(res)
  }
)

function requestHttp(method, url, params, showProgress = true) {
  if (showProgress) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
  }
  return fly.request({
    method: method, // post/get 请求方式
    url: url,
    body: params
  })
}

function uploadFileRequest(url, file, callback) {
  return wx.uploadFile({
    url: host + url,
    filePath: file,
    name: 'file',
    header: {
      "Content-Type": "multipart/form-data"
    },
    success: callback,
    fail: callback
  })
}

fly.config.baseURL = host

export default {
  get(url, params) {
    return requestHttp('GET', url, params)
  },
  post(url, params) {
    return requestHttp('POST', url, params)
  },
  getWithNoProgress(url, params) {
    return requestHttp('GET', url, params, false)
  },
  postWithNoProgress(url, params) {
    return requestHttp('POST', url, params, false)
  },
  uploadFile(url, file, callback) {
    return uploadFileRequest(url, file, callback)
  }
}
